<template>
  <el-dialog v-model="dialogVisible" width="832px">
    <Title :title="dialogTitle" />
    <div class="dialog-container">
      <el-form :model="form" label-width="auto" ref="formRef" size="large" :rules="rules">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>

      <el-form-item label="学院" prop="deptId">
        <el-select v-model="form.deptId" placeholder="请选择学院" @change="onDeptChange" clearable>
          <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="年级" prop="gradeId">
        <el-select v-model="form.gradeId" placeholder="请选择年级" :disabled="!form.deptId" clearable @change="onGradeChange">
          <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="分组教师" prop="teacherIds">
        <el-select v-model="form.teacherIds" multiple placeholder="请选择教师" filterable :disabled="!form.deptId" clearable>
          <el-option v-for="item in teacherOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="分组专业" prop="majorIds">
        <el-select v-model="form.majorIds" multiple placeholder="请选择分组专业" :disabled="!form.gradeId" clearable>
          <el-option v-for="item in majorOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="队伍最大人数" prop="teamMax">
            <el-input-number v-model="form.teamMax" placeholder="请输入队伍最大人数" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="指导队伍数" prop="teacherMax">
            <el-input-number v-model="form.teacherMax" placeholder="请输入指导队伍数" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel" class="defauleButton">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addGroup, updateGroup, getGroup } from '@/api/group'
import { ref, getCurrentInstance, computed } from 'vue'
import { listByDept } from '@/api/teacher'
import { listByGrade } from '@/api/major'
import { getGradeTree } from '@/api/grade'
import Title from '@/components/Title/index.vue'

const { proxy } = getCurrentInstance()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const emit = defineEmits(['update'])

// 存储完整的树形数据
const gradeTree = ref([])
const teacherOptions = ref([])
const majorOptions = ref([])

// 学院选项
const deptOptions = computed(() => {
  return gradeTree.value.map((item) => ({
    label: item.deptName,
    value: item.deptId
  }))
})

// 年级选项：根据选中的学院过滤
const gradeOptions = computed(() => {
  if (!form.value.deptId) return []
  const dept = gradeTree.value.find((item) => item.deptId === form.value.deptId)
  return dept ? dept.children.map((grade) => ({ value: grade.gradeId, label: grade.gradeName })) : []
})

const form = ref({
  deptId: '',
  gradeId: '',
  majorIds: '',
  teacherIds: '',
  groupName: '',
  teamMax: '',
  teacherMax: '',
  startTime: '',
  endTime: '',
  updateBy: '',
  updateTime: '',
  remark: '',
  status: ''
})

const rules = ref({
  groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择学院', trigger: 'change' }],
  gradeId: [{ required: true, message: '请选择年级', trigger: 'change' }]
})
const cancel = () => close()
const confirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const action = form.value.groupId ? updateGroup : addGroup
      const payload = { ...form.value }
      if (Array.isArray(payload.teacherIds)) payload.teacherIds = payload.teacherIds.join(',')
      if (Array.isArray(payload.majorIds)) payload.majorIds = payload.majorIds.join(',')
      action(payload).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        emit('update')
        close()
      })
    }
  })
}
const close = () => (dialogVisible.value = false)
const reset = () => {
  form.value = {
    deptId: '',
    gradeId: '',
    majorIds: '',
    teacherIds: '',
    groupName: '',
    teamMax: '',
    teacherMax: '',
    startTime: '',
    endTime: '',
    updateBy: '',
    updateTime: '',
    remark: '',
    status: ''
  }
  proxy.resetForm('formRef')
}
const init = async (id) => {
  reset()
  dialogTitle.value = id ? '修改分组信息' : '新增分组信息'
  await loadGradeTree()
  if (id) {
    await getDetail(id)
  }
}

const getDetail = async (id) => {
  const res = await getGroup(id)
  const data = res.data || {}

  // 先从 majors 中提取已选择的专业ID
  let selectedMajorIds = []
  majorOptions.value=[]
  if (data.majors && Array.isArray(data.majors) && data.majors.length > 0) {
    selectedMajorIds = data.majors.map(item => item.majorId)
    majorOptions.value.push(...(data.majors).map((item) => ({
      label: item.majorName,
      value: item.majorId
    })))
  }

  form.value = {
    ...form.value,
    ...data,
    teacherIds: typeof data.teacherIds === 'string' && data.teacherIds.length ? data.teacherIds.split(',').map((v) => Number(v)) : Array.isArray(data.teacherIds) ? data.teacherIds : [],
    // 使用从 majors 中提取的专业ID，而不是 majorIds 字符串
    majorIds: selectedMajorIds.length > 0 ? selectedMajorIds : (typeof data.majorIds === 'string' && data.majorIds.length ? data.majorIds.split(',').map((v) => Number(v)) : Array.isArray(data.majorIds) ? data.majorIds : [])
  }

  // 编辑时需要加载对应的教师选项
  if (form.value.deptId) {
    await getTeacherList()
  }

  // 编辑时调用 getMajorList 获取完整的专业列表
  if (form.value.gradeId) {
    await getMajorList()
  }
}

// 加载完整的树形数据
async function loadGradeTree() {
  const res = await getGradeTree()
  gradeTree.value = res.data || []
}

// 根据学院ID获取教师列表
function getTeacherList() {
  if (!form.value.deptId) {
    teacherOptions.value = []
    return Promise.resolve()
  }
  return listByDept(form.value.deptId).then((res) => {
    teacherOptions.value = (res.data).map((item) => ({
      label: item.user?.nickName || item.nickName || item.teachId,
      value: item.teacherId
    }))
  })
}

// 根据年级ID获取专业列表
function getMajorList() {
  if (!form.value.gradeId) {
    majorOptions.value = []
    return Promise.resolve()
  }
  return listByGrade(form.value.gradeId).then((res) => {
    majorOptions.value.push(...(res.data).map((item) => ({
      label: item.majorName,
      value: item.majorId
    })))
  })
}

// 学院改变时的处理
function onDeptChange() {
  // 清空年级、教师、专业的选择
  form.value.gradeId = ''
  form.value.teacherIds = []
  form.value.majorIds = []
  teacherOptions.value = []
  majorOptions.value = []

  // 重新加载教师列表
  getTeacherList()
}

// 年级改变时的处理
function onGradeChange() {
  // 清空专业选择
  form.value.majorIds = []
  majorOptions.value = []

  // 重新加载专业列表
  getMajorList()
}

const openDialog = async (id = null) => {
  await init(id)
   dialogVisible.value = true
}

defineExpose({ openDialog })

// 初始化加载树形数据
loadGradeTree()
</script>
